package com.sayimo.maker.user.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.sayimo.framework.common.Constants;
import com.sayimo.framework.common.MessageObject;
import com.sayimo.framework.exception.DaoException;
import com.sayimo.framework.exception.ServiceException;
import com.sayimo.maker.commons.Constant;
import com.sayimo.maker.commons.utils.CbcEncrypt;
import com.sayimo.maker.commons.utils.JSONUtil;
import com.sayimo.maker.commons.utils.MD5Util;
import com.sayimo.maker.user.dao.CustomerInterfaceDao;
import com.sayimo.maker.user.dao.WalletIncomeExpendRecordInterfaceDao;
import com.sayimo.maker.user.dao.WalletInterfaceDao;
import com.sayimo.maker.user.service.WalletInterfaceService;
import com.sayimo.maker.user.vo.Customer;
import com.sayimo.maker.user.vo.Wallet;
import com.sayimo.maker.user.vo.WalletIncomeExpendRecord;

/**  
 * @Title: WalletInterfaceImplService.java
 * @Package com.sayimo.maker.user.service.impl
 * @Description: 
 * @author 田超
 * @date 2017年2月10日 下午5:13:34
 * @version V1.0  
 */
@Service("walletInterfaceService")
public class WalletInterfaceImplService implements WalletInterfaceService{
	
	private static Log logger = LogFactory.getLog(WalletInterfaceImplService.class);
	@Resource(name="walletInterfaceDao")
	private WalletInterfaceDao walletInterfaceDao;
	@Resource(name="walletIncomeExpendRecordInterfaceDao")
	private WalletIncomeExpendRecordInterfaceDao walletIncomeExpendRecordInterfaceDao;
	@Resource(name="customerInterfaceImplDao")
	private CustomerInterfaceDao customerInterfaceImplDao;
	
	public MessageObject insertWallet(Integer customerId) throws ServiceException {
		MessageObject messageObject = new MessageObject();
		Wallet w = new Wallet();
		w.setCustomerId(customerId);
		try {
			walletInterfaceDao.insertWallet(w);
		} catch (DaoException e) {
			logger.debug(e);
			throw new ServiceException(e);
		}
		messageObject.setKey(Constants.SUCCESS);
		return messageObject;
	}
	
	
	/**
	 * 
	* @Title: updateWalltPassWord
	* @Author: 田超
	* @Date:日期：2017年2月20日 : 下午2:55:17
	* @Description:修改钱包密码
	* @return Map<String,Object>
	* @Version 1.0.0
	 */
	public Map<String,Object> updateWalltPassWord(HttpServletRequest request)throws ServiceException{
		Map<String,Object> resultMap = new HashMap<String, Object>();
		try {
			Integer customerId = Integer.parseInt(request.getParameter("customerId"));
			String newPassword = request.getParameter("newPassword");
			String confirPassword = request.getParameter("confirPassword");
			Customer customer = customerInterfaceImplDao.queryPeopleCode(customerId);
			if(customer != null && (customer.getPeopleCode() == null || customer.getPeopleCode().equals(""))){
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.DATA, Constant.PEOPLE_CARD_NOT_EXIT);
				return resultMap;
			}
			if(customer != null && newPassword.equals(confirPassword)){
				Wallet wallet = new Wallet();
				wallet.setPassWord(newPassword);
				wallet.setCustomerId(customerId);
				Integer num = walletInterfaceDao.updateWallet(wallet);
				if(num > 0){
					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.DATA, Constant.SUCCESS);
				}else{
					resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
					resultMap.put(Constant.DATA, Constant.SELECT_ERROR);
				}
			}else{
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.DATA, Constant.SYSTEM_REQUEST_PARAM_ERROR);  //参数不正确
			}
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
		return resultMap;
	}
	
	
	/**
	 * 
	 * @MethodName setWalletPassword
	 * @Description Description
	 * 
	 * @author chenpy
	 * @date 2015年12月26日 上午10:25:23
	 * @param 
	 * @return MessageObject
	 * @VERSION 1.0.0
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map createWalletPassword(Wallet wallet) throws ServiceException {
		Map resultMap = new HashMap();
		try {
			Wallet w = walletInterfaceDao.queryWalletByCustomerId(wallet.getCustomerId());
			logger.info("wallet = " + JSONUtil.writeValueAsString(w));
			w.setPassWord(MD5Util.MD5Encode(CbcEncrypt.encrypt(wallet.getPassWord()), "UTF-8"));
			int result = walletInterfaceDao.updateWallet(w);
			Map msgMap = new HashMap();
			if (result > 0) {
				msgMap.put(Constant.MSG, "设置成功");
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, msgMap);
				return resultMap;
			}
			msgMap.put(Constant.MSG, "设置失败");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.DATA, msgMap);
			return resultMap;
		} catch (Exception e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	
	/** 
	 * @author 陈培永
	 * @Title: queryWalletInfo
	 * @Description: 获取用户钱包信息
	 * @param paramCustomer
	 * @throws ServiceException
	 * @return Customer 
	 */ 
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map queryWalletInfo(int customerId) throws ServiceException{
		Map resultMap = new HashMap();
		try {
			Map<String, Object> dataMap = walletInterfaceDao.queryWalletInfo(customerId);
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, dataMap);
			return resultMap;
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/** 
	 * @author 陈培永
	 * @Title: updateMoneyPwd
	 * @Description: 修改提现密码
	 * @return String 
	 */ 
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map updateMoneyPwd(Wallet paramWallet) throws ServiceException{
		Map resultMap = new HashMap();
		// 比较原始密码是否正确
		try {
			Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(paramWallet.getCustomerId());
			
			if (!wallet.getPassWord().equals(paramWallet.getOldPassword())) { // 原始密码不正确
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.WALLET_OLD_PWD_ERROR);
				return resultMap;
			}
			
			paramWallet.setId(wallet.getId());
			paramWallet.setPassWord(paramWallet.getPassWord());
			logger.info("wallet = " + JSONUtil.writeValueAsString(paramWallet));
			int result = updateWallet(paramWallet);
			Map msgMap = new HashMap();
			if (result > 0) {
				msgMap.put(Constant.MSG, "修改成功");
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, msgMap);
				return resultMap;
			}
			
			msgMap.put(Constant.MSG, "修改失败");
			resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
			resultMap.put(Constant.DATA, msgMap);
			return resultMap;
			
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/** 
	 * @author 陈培永
	 * @Title: listWalletInOutDetail
	 * @Description: 收支明细记录
	 * @return String 
	 */ 
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map listWalletInOutDetail(int customerId, Integer queryType,Integer rewardType,String orderType,Integer pageNow,Integer pageSize,String transferStatus) throws ServiceException{
		Map resultMap = new HashMap();
		Map  data = new HashMap();
		
		try {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("customerId", customerId);
			paramMap.put("queryType", queryType);
			paramMap.put("rewardType", rewardType);
			if(orderType!=null){
				paramMap.put("orderType", orderType);
			}
			if(transferStatus!=null && !"".equals(transferStatus)){
				paramMap.put("transferStatus", Integer.valueOf(transferStatus));
			}
			if(pageNow != null && pageNow == 0){
				paramMap.put("pageNow", 0);
			}else if(pageNow != null && pageNow > 0){
				paramMap.put("pageNow", (pageNow-1)*pageSize);
			}
			if(pageSize != null){
				paramMap.put("pageSize", pageSize);
			}
			//获取交易记录
			List<WalletIncomeExpendRecord> expendRecords = walletIncomeExpendRecordInterfaceDao.queryWalletInOutByCond(paramMap);
			List<Map> dataList = new ArrayList<Map>();
			if (CollectionUtils.isEmpty(expendRecords)) {
				data.put("dataList",dataList);
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA,data);
				return resultMap;
			}
			
			for (WalletIncomeExpendRecord incomeExpendRecord : expendRecords) {
				Map dataMap = new HashMap();
				dataMap.put("emsNo", incomeExpendRecord.getEmsNo());
				dataMap.put("createDate", incomeExpendRecord.getCreateDate().getTime());
				dataMap.put("inCome", incomeExpendRecord.getInCome() == null ? "" : incomeExpendRecord.getInCome());
				dataMap.put("exPend", incomeExpendRecord.getExPend() == null ? "" : incomeExpendRecord.getExPend());
				dataMap.put("commet", incomeExpendRecord.getCommet() == null ? "" :incomeExpendRecord.getCommet());
				dataMap.put("rewardType", incomeExpendRecord.getRewardType() == null ? "" : incomeExpendRecord.getRewardType());
				dataMap.put("fromType", incomeExpendRecord.getFromType());
				dataMap.put("providerName", incomeExpendRecord.getProviderName() == null ? "" :incomeExpendRecord.getProviderName());
				dataMap.put("alias", incomeExpendRecord.getAlias() == null ? "" :incomeExpendRecord.getAlias());
				dataMap.put("singleTurnover", incomeExpendRecord.getSingleTurnover() == null ? "" :incomeExpendRecord.getSingleTurnover());
				dataMap.put("ordersNo", incomeExpendRecord.getOrdersNo() == null ? "" :incomeExpendRecord.getOrdersNo());
				dataMap.put("mallType", incomeExpendRecord.getMallType() == null ? "" :incomeExpendRecord.getMallType());
				dataMap.put("transferStatus", incomeExpendRecord.getTransferStatus() == null ? "" :incomeExpendRecord.getTransferStatus());
				dataMap.put("failureCause", incomeExpendRecord.getFailureCause() == null ? "" :incomeExpendRecord.getFailureCause());
				
				dataList.add(dataMap);
			}
			data.put("dataList",dataList);	
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, data);
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			throw new ServiceException(e);
		}
		
	}

	/* (non-Javadoc)
	 * @see com.sayimo.school.mall.module.admin.service.WalletInterfaceService#queryWalletByCustomerId(int)
	 */
	public Wallet queryWalletByCustomerId(int customerId) throws ServiceException {
		try {
			return this.walletInterfaceDao.queryWalletByCustomerId(customerId);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	
	/** 
	 * @author 陈培永
	 * @Title: updateWallet
	 * @Description: 修改钱包
	 * @return String 
	 */ 
	public int updateWallet(Wallet wallet) throws ServiceException {
		try {
			return this.walletInterfaceDao.updateWallet(wallet);
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
	/**
	 * @Package com.sayimo.maker.user.service.impl
	 * @Author 谭新
	 * @MethodName: verifyMoneyPwd
	 * @Description:验证钱包密码
	 * @Date 2017年3月22日,上午11:46:52
	 */
	public Map verifyMoneyPwd(Wallet paramWallet) throws ServiceException{
		Map resultMap = new HashMap();
		// 比较密码是否正确
		try {
			Wallet wallet = walletInterfaceDao.queryWalletByCustomerId(paramWallet.getCustomerId());
			
			if (!wallet.getPassWord().equals(paramWallet.getPassWord())) { // 原始密码不正确
				resultMap.put(Constant.STATUS, Constant.STATUS_ERROR);
				resultMap.put(Constant.ERROR_CODE, Constant.WALLET_OLD_PWD_ERROR);
				return resultMap;
			}
			resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
			resultMap.put(Constant.DATA, Constant.SUCCESS);
			return resultMap;
			
		} catch (DaoException e) {
			logger.error(e);
			throw new ServiceException(e);
		}
	}
}
